package com.ladlee.mobile;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.SecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.DefaultSecurityFilterChain;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.stereotype.Component;

/**
 * @Auther: dingchang
 * @Date: 2018/12/26 17:57
 * @Description: 短信登陆验证配置类
 */
@Component
public class SmsAuthenticationSecurityConfig extends SecurityConfigurerAdapter<DefaultSecurityFilterChain, HttpSecurity> {

    @Autowired
    UserDetailsService userDetailsService;

    @Autowired
    AuthenticationFailureHandler loginFailHandler;

    @Override
    public void configure(HttpSecurity builder) throws Exception {
        //自定义SmsAuthenticationFilter过滤器
        SmsAuthenticationFilter smsAuthenticationFilter = new SmsAuthenticationFilter();
        /**
         * AuthenticationManager 接收 Authentication 对象作为参数，并通过 authenticate(Authentication) 方法对其进行验证；
         * AuthenticationProvider实现类用来支撑对 Authentication 对象的验证动作；
         * UsernamePasswordAuthenticationToken（或者自定义SmsAuthenticationToken）实现了 Authentication主要是将用户输入的用户名和密码进行封装，并供给 AuthenticationManager 进行验证；
         * 验证完成以后将返回一个认证成功的 Authentication 对象；
         */
        smsAuthenticationFilter.setAuthenticationManager(builder.getSharedObject(AuthenticationManager.class));//注入用户验证对象AuthenticationManager
        //注入失败处理器
        smsAuthenticationFilter.setAuthenticationFailureHandler(loginFailHandler);

        //设置自定义SmsAuthenticationProvider的认证器userDetailsService
        SmsAuthenticationProvider smsAuthenticationProvider = new SmsAuthenticationProvider();
        smsAuthenticationProvider.setUserDetailsService(userDetailsService);
        //设置在UsernamePasswordAuthenticationFilter过滤前执行
        builder.authenticationProvider(smsAuthenticationProvider).addFilterBefore(smsAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
    }
}
